﻿var liveChatOperator = {

    config: {
        welcomeMessage: null,
        playSounds: true,
        sessionId: null,
        chargeId: null
    },

    initMenu: function() {

        $('#link-playSounds').click(function () {
            if ($(this).children('i').hasClass('icon-volume-up')) {
                liveChatOperator.config.playSounds = false;
                $(this).children('i').removeClass('icon-volume-up');
                $(this).children('i').addClass('icon-volume-off');
            } else {
                liveChatOperator.config.playSounds = true;
                $(this).children('i').removeClass('icon-volume-off');
                $(this).children('i').addClass('icon-volume-up');
            }
        });

        $('#link-bannedClients').click(function () {
            liveChatOperator.loadBannedClients(false);
        });
        
        $('#link-cannedResponses').click(function () {
            liveChatOperator.loadCannedResponses(true);
        });

        $('#btn-addCannedResponseMessage').click(function () {
            liveChatOperator.insertCannedResponse($('#text-cannedResponseMessage').val());
        });
        
        $('#link-transcriptHistory').click(function () {
            liveChatOperator.loadTranscripts(false);
            $('html, body').animate({
                scrollTop: $("#transcripts-container").offset().top
            }, 2000);
        });

    },

    loadTranscripts: function(getRecent) {

        $.getJSON('/loadtranscripts', { getRecent: getRecent }, function (data)
        {
            if (data.transcripts.length > 0) {
                $('#transcripts').html('');
                for (var i = 0; i < data.transcripts.length; i++) {
                    $('#transcripts').append('<tr><td>' + data.transcripts[i].Name + '</td><td>' + data.transcripts[i].Email + '</td><td>' + data.transcripts[i].OperatingSystem + '</td><td>' + data.transcripts[i].Browser + '</td><td><button class="btn btn-mini btn-danger" data-clientname="' + data.transcripts[i].Name + '" data-clientip="' + data.transcripts[i].ClientIp + '"><i class="icon-ban-circle"></i></button> ' + data.transcripts[i].ClientIp + '</td><td><span class="time" title="' + data.transcripts[i].ConnectedAt + '">' + data.transcripts[i].ConnectedAt + '</span></td><td><button class="btn btn-mini pull-right btn-block" data-clientChatId="' + data.transcripts[i].Id + '">Open</button></td></tr>');
                }
                $("span.time").prettyDate();
                $('[data-clientChatId]').click(function () {
                    $.getJSON('/loadTranscript', { clientChatLogId: $(this).attr('data-clientChatId') }, function (data)
                    {
                        $('#transcriptMessagesContainer').html('');
                        if (data.messages.length > 0) {
                            for (var i = 0; i < data.messages.length; i++) {
                                $('#transcriptMessagesContainer').append('<tr><td>' + data.messages[i].Recipient + '</td><td>' + data.messages[i].Sender + '</td><td>' + data.messages[i].Message + '</td><td>' + data.messages[i].TimeStampJS + '</td></tr>');
                            }
                        }
                        $('#modalTranscript').modal('show');
                    }); 
                });
                $('[data-clientip]').click(function () {
                    liveChatOperator.insertBannedClient($(this).attr('data-clientname'), $(this).attr('data-clientip'));
                });
            } else {
                $('#transcripts').html('<tr><td colspan="6">No transcripts found.</td></tr>');
            }
        });
       
    },

    loadBannedClients: function (justAdded) {

        $('#alertJustAdded').hide();
        $('#modalBannedClients').modal('show');

        if (justAdded)
            $('#alertJustAdded').show();

        $.getJSON('/loadbannedclients', function (data) {
            if (data.bannedClients.length > 0) {
                $('#bannedClientsContainer').html('');
                for (var i = 0; i < data.bannedClients.length; i++) {
                    $('#bannedClientsContainer').append('<tr><td>' + data.bannedClients[i].Name + '</td><td>' + data.bannedClients[i].ClientIp + '</td><td>' + data.bannedClients[i].BannedOn + '</td><td><button class="btn btn-mini btn-block" data-bannedclientid="' + data.bannedClients[i].Id + '">Remove Ban</button></td></tr>');
                }
                $('[data-bannedclientid]').click(function() {
                    liveChatOperator.removeBannedClient($(this).attr('data-bannedclientid'));
                });
            } else {
                $('#bannedClientsContainer').html('<tr><td colspan="6">No banned clients found.</td></tr>');
            }
        });

    },

    loadCannedResponses: function (showWindow) {

        if (showWindow)
            $('#modalCannedRespones').modal('show');

        $.getJSON('/loadcannedresponses', function (data) {
            if (data.cannedResponses.length > 0) {

                $('#cannedResponsesDropdown').show();
                $('#cannedResponses').html('');
                $('#cannedResponsesContainer').html('');

                for (var i = 0; i < data.cannedResponses.length; i++) {
                    $('#cannedResponsesContainer').append('<tr><td>' + (i + 1) + '.</td><td>' + data.cannedResponses[i].Message + '</td><td></td></tr>');
                    $('#cannedResponses').append('<li><a href="javascript:void(0)" class="link-cannedresponse">' + data.cannedResponses[i].Message + '</a></li>');

                }
            } else {
                $('#cannedResponsesDropdown').hide();
                $('#cannedResponsesContainer').html('<tr><td colspan="2">No canned responses found.</td></tr>');
            }

            $('.link-cannedresponse').click(function () {
                $('#textLiveChatMessage').val($(this).text());
            });
            
        });

    },

    insertCannedResponse: function (message) {

        if (message.length > 0) {
            $.getJSON('/insertcannedresponse', { message: message }, function (data) {
                liveChatOperator.loadCannedResponses(true);
            })
        }

    },

    insertBannedClient: function(name, clientIp) {

        if (liveChatOperator.config.chargeId.length > 0) {
            $.getJSON('/insertbannedclient', { name: name, clientIp: clientIp }, function (data) {
                liveChatOperator.loadBannedClients(true);
            })
        } else {
            $('#modalUpgrade').modal('show');
        }

    },

    removeBannedClient: function (id) {

        $.getJSON('/removebannedclient', { Id: id }, function (data) {
            liveChatOperator.loadBannedClients(false);
        })

    },

    init: function (newConfig) {

        if (typeof (newConfig == 'object'))
            this.config = newConfig;

        liveChatOperator.initMenu();
        liveChatOperator.loadTranscripts(true);

        var liveChat = $.connection.livechat;
        var activeChatConnectionId;
        var sessionId;
        var inChat = false;
        var typingIndicationTimer;
        var keyStrokeCount = 0;

        var liveChatMessages = {

            appendMessageToChatWindow: function (sender, message) {
                $('#liveChatText').append('<div class="messageContainer row-fluid"><div class="span4"><i class="icon-chevron-right"></i>&nbsp;&nbsp;<strong>' + sender + '</strong><br /><span class="time" title="' + new Date().toISOString() + '">' + new Date().toISOString() + '</span></div><div class="span8">' + message + '</div></div>');
            },

            appendInfoMessageToChatWindow: function (message) {
                $('#liveChatText').append('<div class="alert alert-info">' + message + '</div>');
            },

            appendAlertMessageToChatWindow: function (message) {
                $('#liveChatText').append('<div class="alert">' + message + '</div>');
            }

        };

        $.connection.hub.start(function () {

            setInterval(function () { liveChat.server.keepAlive(); }, 30000);

            $('#modalOperatorName').modal('show');
            $('#textOperatorName').val($.cookie("operator-name"))

            liveChat.server.loadAllClients();
            $('#btnStartOperatorChat').click(function () {
                $.cookie("operator-name", $('#textOperatorName').val(), { path: "/" });
                liveChat.server.operatorJoin($('#textOperatorName').val(), liveChatOperator.config.chargeId);
                $('#modalOperatorName').modal('hide');
                $('#label-operatorName').text($('#textOperatorName').val());
            });

        });

        liveChat.client.showUpgradeDialog = function () {
            $('#label-operatorName').text('n/a');
            $('#modalUpgrade').modal('show');
        };

        liveChat.client.loadAllOperators = function (operators) {
            $('#operatorsList').html('');
            $.each(operators, function (index) {
                var chatStatus = '';
                if (operators[index].InChat == true)
                    chatStatus = '<label class="label label-success">In Chat</label> ';
                $('#operatorsList').append('<li><a href="javascript:void(0)">' + chatStatus + operators[index].Name + '</a></li>');

            });
        };

        liveChat.client.postMessage = function (message, senderId, senderName, messageType) {

            if (messageType == 'info') {
                liveChatMessages.appendInfoMessageToChatWindow(message);
            } else {
                liveChatMessages.appendMessageToChatWindow(senderName, message);
            }

            activeChatConnectionId = senderId;
            $("#liveChatText").animate({ scrollTop: $('#liveChatText')[0].scrollHeight }, 1000);
            $("span.time").prettyDate();

            $('#typing-indicator-operator').slideUp();
            clearTimeout(typingIndicationTimer);
            keyStrokeCount = 0;
        };

        liveChat.client.sessionUpdate = function (status) {
            if (status == 'false')
                window.location = '/membership/login';
        };

        liveChat.client.updateSessionId = function (sessionId) {
            liveChatOperator.config.sessionId = sessionId;
        };

        liveChat.client.playOperatorNotification = function () {

            if (liveChatOperator.config.playSounds == true)
                $('#chatAudio')[0].play();
        };

        liveChat.client.isTyping = function () {
            $('#typing-indicator-operator').slideDown();
            clearTimeout(typingIndicationTimer);
            typingIndicationTimer = setTimeout(function () { $('#typing-indicator-operator').slideUp(); }, 2000);
        };

        liveChat.client.loadAllClients = function (clients) {

            $('#chatQueue').html('');
            liveChatOperator.loadTranscripts(true);

            if (clients.length > 0)
            {

                $.each(clients, function (index) {

                    var chatStatus = '';
                    if (clients[index].OperatorConnectionId != null)
                        chatStatus = '<label class="label label-success">In Chat</label> ';

                    //Needs refactor. data- information should be loaded once chat is initialized.
                    $('#chatQueue').append('<li><a href="javascript:void(0)" data-url="' + clients[index].Url + '" data-clientOperatingSystem="' + clients[index].OperatingSystem + '" data-clientBrowser="' + clients[index].Browser + '" data-operatorId="' + clients[index].OperatorConnectionId + '" data-clientEmail="' + clients[index].Email + '" data-clientName="' + clients[index].Name + '" data-clientConnectionId="' + clients[index].ConnectionId + '"><i class="icon-chevron-right"></i> ' + chatStatus + clients[index].Name + ' - <span class="time" title="' + clients[index].ConnectedAt + '">' + clients[index].ConnectedAt + '</span></a></li>');
                });

                $('[data-clientConnectionId]').click(function () {

                    if (inChat)
                    {
                        alert('You are already engadged in a client chat.');
                        return;
                    }

                    if ($(this).attr('data-operatorId') == 'null') {

                        $('#noChatText').hide();
                        $('#chatText').fadeIn();

                        $('#liveChatText').html('');
                        activeChatConnectionId = $(this).attr('data-clientConnectionId');
                        liveChat.server.startClientChat(activeChatConnectionId, $.connection.hub.id);
                        liveChatMessages.appendInfoMessageToChatWindow('Now chatting with <strong>' + $(this).attr('data-clientName') + '</strong> (' + $(this).attr('data-clientEmail') + ')<br />Browser: ' + $(this).attr('data-clientBrowser') + '<br />OS: ' + $(this).attr('data-clientOperatingSystem') + '<br />' + $(this).attr('data-url'));

                        $('#textLiveChatMessage').css('width', $('#containerLiveChat').width() - 100 + 'px');

                        $("#textLiveChatMessage").val(liveChatOperator.config.welcomeMessage);
                        $("#textLiveChatMessage").keypress(function (e) {
                            
                            keyStrokeCount++;
                            if (keyStrokeCount > 10) {
                                liveChat.server.isTyping($.connection.hub.id, activeChatConnectionId)
                                keyStrokeCount = 0;
                            }

                            if (e.which == 13) {
                                e.preventDefault();
                                $('#btnSendChatMessage').trigger('click');
                            }

                        });
                        
                        inChat = true;
                        liveChatOperator.loadCannedResponses(false);                        
                    }

                });

                $("span.time").prettyDate();
            }

        };

        $('#btnSendChatMessage').click(function () {
            var message = $('#textLiveChatMessage').val();
            if (message != '') {

                $('#textLiveChatMessage').val('');
                liveChatMessages.appendMessageToChatWindow($.cookie("operator-name"), message);
                liveChat.server.sendMessage(message, activeChatConnectionId, $.connection.hub.id, $.cookie("operator-name"), '', liveChatOperator.config.sessionId);
                $("#liveChatText").animate({ scrollTop: $('#liveChatText')[0].scrollHeight }, 1000);
                $("span.time").prettyDate();

                geturl = new RegExp(
                          "(^|[ \t\r\n])((http|https):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))"
                         , "g"
                       );

                if (message.match(geturl) != null)
                    liveChat.server.sendUrl(message.match(geturl)[0], activeChatConnectionId);

            }
        })

        $('#link-EndChat').click(function () {
            liveChat.server.endChat(activeChatConnectionId);
            $('#liveChatText').html('');
            $('#noChatText').fadeIn();
            $('#chatText').hide();
            inChat = false;
        });
    }
}